using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SharpMap.Presentation.Wpf;
using SharpMap.Styles;
using SharpMap.Tools;
using Microsoft.Win32;
using SharpMap.Layers;
using SharpMap.Data.Providers.GeometryProvider;
using SharpMap.Data;
using System.Windows.Interop;
using IO = System.IO;
using GeoPoint = SharpMap.Geometries.Point;
using WpfMatrix = System.Windows.Media.Matrix;
using WpfSize = System.Windows.Size;
using WpfRect = System.Windows.Rect;
using WpfDrawing = System.Windows.Media.Drawing;
using SharpMap.Wpf;
using System.Reflection;
using SharpMap.Data.Providers.FeatureProvider;


namespace CoreDemoWpf
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>

    public partial class Window1 : System.Windows.Window, System.Windows.Forms.IWin32Window
    {
        static Window1()
        {
          
        }

        FeatureProvider _fp;
        public Window1()
        {
            InitializeComponent();

            

            _topPanel.LastChildFill = true;
            DockPanel.SetDock(m_mapView, Dock.Bottom);

           //_grid.Children.Add(m_mapView);
           Grid.SetColumn(m_mapView, 1);
           Grid.SetRowSpan(m_mapView, 2);
           
           m_mapView.Margin = new Thickness(3);
           SharpMap.Wpf.Thematics.CitiesTheme theme = new SharpMap.Wpf.Thematics.CitiesTheme();
            
           //_citiesTheme.MapView = m_mapView;
           m_mapView.Theme = theme;

           InitializeFeatureProvider();
        }

        private void InitializeFeatureProvider()
        {
            System.Data.DataColumn c1 = new System.Data.DataColumn("Name",typeof(string));
            _fp = new FeatureProvider(new System.Data.DataColumn[] { c1 });
        }

        void WindowLoaded(object sender, RoutedEventArgs e)
        {
            loadMap();
        }
  

        SharpMap.Map m_map;
        void loadMap()
        {

            m_map = new SharpMap.Map();
   
    
            Assembly entryAssembly = Assembly.GetEntryAssembly();
            string exePath = IO.Path.GetDirectoryName(entryAssembly.Location);
  
           //
           // Cities
           //


            string citiesShapeFile = @"..\..\..\TestData\cities.shp";
            GeometryLayer cities = LoadLayer(citiesShapeFile, "Cities");
            cities.DataSource.Open();
            m_map.AddLayer(cities);
            //m_mapView.Map.AddLayer(cities);
 
            //
            //countries
            //
            VectorStyle s = new VectorStyle();
            String fileFullPath = IO.Path.Combine(exePath , @"..\..\..\TestData\world_adm0.shp");
            GeometryLayer countries = LoadCountries(fileFullPath, s);
            m_map.AddLayer(countries);

            //
            // detailed countries layer
            //
            //fileFullPath = exePath + @"\..\..\..\TestData\cntry00.shp";
            //s = LoadDetailedLayer(fileFullPath, s);

            m_mapView.Map = m_map;
            this.DataContext = m_map;
  
            m_mapView.BackgroundColor = SharpMap.Styles.StyleColor.Blue;
            m_mapView.WorldWidth = 40;
           // m_mapView.ZoomToExtents();
            
            

            
        }

        private GeometryLayer LoadCountries(String fileFullPath, VectorStyle s)
        {
            GeometryLayer countries = LoadLayer(fileFullPath, "Countries");


            //s.MinVisible = 50;
            s.Fill = new SolidStyleBrush(StyleColor.Gray);
            s.Outline = new StylePen(StyleColor.Yellow, 0.5);
            //s.Line = new StylePen(StyleColor.Yellow, 0.5);
            s.HighlightFill = new SolidStyleBrush(StyleColor.YellowGreen);
            s.SelectFill = new SolidStyleBrush(StyleColor.BlueViolet);
            s.EnableOutline = false;
            countries.Style = s;
            countries.Style.AreFeaturesSelectable = false;

            countries.DataSource.Open();
            return countries;
        }

        private VectorStyle LoadDetailedLayer(String fileFullPath, VectorStyle s)
        {
            GeometryLayer detailedCountries = LoadLayer(fileFullPath, "DetailedCountries");
            s = new VectorStyle();
            //s.MaxVisible = 0;
            s.MaxVisible = 50;
            s.Fill = new SolidStyleBrush(StyleColor.Gray);
            s.Outline = new StylePen(StyleColor.Yellow, 0.5);
            //s.Line = new StylePen(StyleColor.Yellow, 0.5);
            s.HighlightFill = new SolidStyleBrush(StyleColor.YellowGreen);
            s.SelectFill = new SolidStyleBrush(StyleColor.BlueViolet);

            s.AreFeaturesSelectable = false;


            detailedCountries.Style = s;
            detailedCountries.DataSource.Open();
            m_mapView.Map.AddLayer(detailedCountries);
            return s;
        }

        private void PanToolStripButton_Click(object sender, RoutedEventArgs e)
        {
            changeMode(StandardMapTools2D.Pan);
        }

        
        private void QueryToolClicked(object sender, RoutedEventArgs e)
        {
            changeMode(WpfMapTools.SelectRectangle);
        }
        private void changeMode(SharpMap.Tools.MapTool tool)
        {
            //m_mapView.Map.ActiveTool
            m_mapView.Map.ActiveTool = tool;
            panToolStripButton.IsChecked = (tool == WpfMapTools.Pan);
            zoomMouseModeToolStripButton.IsChecked = (tool == WpfMapTools.ZoomMouse);
            zoomRectangleModeToolStripButton.IsChecked = (tool == WpfMapTools.ZoomRectangle);
            panToolStripButton.IsChecked = (tool == WpfMapTools.Pan);
            _selectToolStripButton.IsChecked = (tool == WpfMapTools.SelectRectangle);
            _measureToolStripButton.IsChecked = (tool == WpfMapTools.MeasureDistance);


            if ( (bool)_selectToolStripButton.IsChecked)
            {
                m_mapView.Map.DeselectLayers(m_mapView.Map.SelectedLayers);
                m_mapView.Map.SelectLayer(m_mapView.Map.Layers[m_mapView.Map.Layers.Count - 1]);
            }
        }
        
        private SharpMap.Layers.GeometryLayer LoadLayer(String fileName, string givenLayerName)
        {
            SharpMap.Data.Providers.ShapeFile.ShapeFileProvider shapFile =
            new SharpMap.Data.Providers.ShapeFile.ShapeFileProvider(fileName);
            
            String layerName = givenLayerName ?? fileName.Substring(fileName.LastIndexOf('\\') + 1);

            SharpMap.Layers.GeometryLayer layer = new SharpMap.Layers.GeometryLayer(layerName, shapFile);
            return layer;
        }

        private void NewLayer(string layerName)
        {
          //  FeatureDataTable table = new FeatureDataTable();
          //  table.Columns.Add("oid");
          //  table.Columns.Add("name");
          //  table.Columns.Add("lon");
          //  table.Columns.Add("lat");
            
          //  for (int i = 10; i <= 30; i+=10)
          //  {
          //      for (int j = 10; j <= 30; j+=10)
          //      {
          //              FeatureDataRow fdr = table.NewRow();
          //              fdr.BeginEdit();
          //              fdr["oid"]=i*10+j;
          //              fdr["lon"]=i;
          //              fdr["lat"]=j;
          //              fdr["name"]="point(" + i + "," +j + ")" ;
          //              fdr.EndEdit();
          //      }
          //  }
          //  table.AcceptChanges();
       
          //  SharpMap.Data.Providers.FeatureProvider.FeatureProvider fp = 
          //      new SharpMap.Data.Providers.FeatureProvider.FeatureProvider(table.Columns);

          //  layerName = layerName + m_mapControl.Map.Layers.Count.ToString();
            
          //  SharpMap.Layers.GeometryLayer layer = new SharpMap.Layers.GeometryLayer(layerName, fp);
          //  VectorStyle s = new VectorStyle();
          //  s.EnableOutline = true;
          
          //  StyleBrush nullbrush = new SolidStyleBrush(StyleColor.Transparent);
          //  s.Fill = nullbrush;
          //  s.Outline = new StylePen(StyleColor.Yellow, 0.5);
          //  s.Line = new StylePen(StyleColor.Yellow, 0.5);
          
          //  //new StylePen(nullbrush, 0.001);
          //  //s.Outline.DashStyle = LineDashStyle.DashDot;

          //  layer.Style = s;
            
          
          //layer.AsyncQuery = false;
          
          //  m_mapControl.Map.AddLayer(layer);
        }

        private void MenuItemClick(object sender, RoutedEventArgs e)
        {
            //m_mapView.Diagnoze();
        }
        System.Windows.Forms.Form _form = null;
 

 
        #region IWin32Window Members
        IntPtr _handle = IntPtr.Zero;
        public IntPtr Handle
        {
            get 
            {
                if(_handle.Equals(IntPtr.Zero))
                {
                    System.Windows.Interop.IWin32Window wpfHwnd = HwndSource.FromVisual(this) as IWin32Window;
                    _handle = wpfHwnd.Handle;
                    
                }

                return _handle;
            }
        }

        #endregion
       

        private void _drag_Click(object sender, RoutedEventArgs e)
        {
            changeMode(WpfMapTools.MoveObject);
        }

        private void _measure_Click(object sender, RoutedEventArgs e)
        {
            changeMode(WpfMapTools.MeasureDistance);
        }
        private void zoomMouseModeToolStripButton_Click(object sender, RoutedEventArgs e)
        {
            changeMode(WpfMapTools.ZoomMouse);
        }
          private void _select_Click(object sender, RoutedEventArgs e)
        {
            changeMode(WpfMapTools.SelectRectangle);
        }
          private void panClick(object sender, RoutedEventArgs e)
          {
              changeMode(WpfMapTools.Pan);
          }
          private void ZoomRectangleClicked(object sender, RoutedEventArgs e)
          {
              changeMode(WpfMapTools.ZoomRectangle);
          }
          private void zoomToWorldBounds_Click(object sender, RoutedEventArgs e)
          {
              MapViewCommands.ZoomToWorldBounds.Execute(
                  new SharpMap.Geometries.BoundingBox(30, 30, 40, 40)
                        , m_mapView);
              
          }

          private void zoomToViewBounds_Click(object sender, RoutedEventArgs e)
          {
              SharpMap.Rendering.Rendering2D.Rectangle2D bounds = new SharpMap.Rendering.Rendering2D.Rectangle2D(10, 10
              , m_mapView.ActualWidth -10, m_mapView.ActualHeight - 10);
              
              m_mapView.ZoomToViewBounds(bounds);
          }

          private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
          {

          }

          private void AddLayerHadler(object sender, RoutedEventArgs e)
          {
              NewLayer("NewLayer");
          }

   

          private void MenuItem_Click_1(object sender, RoutedEventArgs e)
          {
              SharpMap.Geometries.LineString ls = new SharpMap.Geometries.LineString();
              SharpMap.Rendering.Rendering2D.Path2D path = new SharpMap.Rendering.Rendering2D.Path2D();
              path.AddPoint(new SharpMap.Rendering.Rendering2D.Point2D(32, 32));
              path.AddPoint(new SharpMap.Rendering.Rendering2D.Point2D(-40, 50));
             
          }

          private void _zoomToButton_Click(object sender, RoutedEventArgs e)
          {
              //if (_kindOfZoom.Text == "World Width")
              //{
              //    double res;
              //    if(double.TryParse(_zoomValueTextBox.Text,out res))
              //    {
              //        MapViewCommands.ZoomToWorldWidth.Execute(res,m_mapView);
              //    }
              //}
           }

          private void _kindOfZoom_SelectionChanged(object sender, SelectionChangedEventArgs e)
          {
              //if (_kindOfZoom.Text == "World Width")
              //{
              //    _zoomValueTextBox.Text = m_mapView.WorldWidth.ToString();
              //}
              //if (_kindOfZoom.Text == "World Bounds")
              //{
                     
              //    Rect rc=    new Rect(m_mapView.ViewEnvelope.Left,m_mapView.ViewEnvelope.Top
              //        ,m_mapView.ViewEnvelope.Width,m_mapView.ViewEnvelope.Height);
              //    _zoomValueTextBox.Text = rc.ToString();                     
              //}
          }

        
         
    }
}
